package cn.bdqn.auth_consumer.controller;

import cn.bdqn.auth_consumer.service.UserService;
import cn.bdqn.common.Constants;
import cn.bdqn.common.Dto;
import cn.bdqn.common.DtoUtil;
import cn.bdqn.vo.TokenVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * 2018/9/20
 */
@Api(value="/api", tags="用户接口模块")
@RestController
@RequestMapping("/api")
public class UserController {


    @Resource
    private UserService userService;

    /**
     * 登录功能
     * @param phone
     * @param password
     * @param request
     * @return
     */
    @ApiOperation(value="用户登录实现",httpMethod = "POST", protocols = "HTTP", produces = "application/json", response = Dto.class,notes="用户登录")
    @RequestMapping(value = "/doLogin", method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto doLogin(@RequestParam String phone, @RequestParam String password, HttpServletRequest request){
        String token = null;
        try {
            token = userService.login(phone,password);
        } catch (Exception e) {
           return DtoUtil.returnFail(e.getMessage(),"10086");
        }
        TokenVo tokenVo = new TokenVo(token,Calendar.getInstance().getTimeInMillis()+ Constants.TOKEN_VALID_TIME,Calendar.getInstance().getTimeInMillis());
        return DtoUtil.returnDataSuccess(tokenVo);

    }

    /**
     * 注销
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value="用户注销实现",httpMethod = "GET", protocols = "HTTP", produces = "application/json", response = Dto.class,notes="用户注销")
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    @ResponseBody
    public Dto logout(HttpServletRequest request) throws Exception {
        try {
            userService.logOut(request.getHeader("token"));
        } catch (Exception e) {
            return DtoUtil.returnFail("注销失败","10086");
        }
        return DtoUtil.returnSuccess("注销成功！");
    }

    /**
     * token置换
     * @param request
     * @return
     */
    @ApiOperation(value = "token验证置换",httpMethod = "POST")
    @RequestMapping(value = "/retoken",method = RequestMethod.POST)
    @ResponseBody
    public Dto replacement(HttpServletRequest request) {
        TokenVo tokenVo = null;
        try {
            tokenVo = userService.reToken(request.getHeader("token"));
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), "10086");
        }
        return DtoUtil.returnSuccess("置换成功！", tokenVo);
    }
}
